package net.wanho.interceptor;

import cn.hutool.core.util.ObjectUtil;
import net.wanho.constant.UserConstant;
import net.wanho.exception.UnauthorizedException;
import net.wanho.util.JwtUtil;
import net.wanho.util.ThreadUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String authorization = request.getHeader("authorization");
        if (ObjectUtil.isEmpty(authorization)){
            throw new UnauthorizedException("请先登录在操作");
        }

        String token = authorization.replace("Bearer ", "");
        if(!JwtUtil.valid(token)){
            throw new UnauthorizedException("登录无效，请重新登录");
        }

        Integer id = JwtUtil.parseInteger(token, UserConstant.USER_ID);
        System.out.println("id:"+id);
        ThreadUtil.setId(id);
        return true;
    }
}
